/* Type.cpp
Copyright (c) 2008 Michael Zahniser
Please note the license terms (MIT license) at the end of this document.

Function definitions for the Type class.
*/

#include "Type.h"

#include "_common/int_types.h"

#include <sstream>
#include <algorithm>
#include <cstring>

using std::ostringstream;
using std::hex;
using std::copy;
using std::reverse_copy;
using std::memcpy;

namespace {
	template <class T>
	T to(char *data)
	{
		T result;
		memcpy(&result, data, sizeof(T));
		return result;
	}
}



// SetBigEndian:
// Set all types to big-endian mode.
// The default is little-endian.
void Type::SetBigEndian(bool isBigEndian)
{
	bigEndian = isBigEndian;
}



// IsBigEndian:
// Check whether Type is set to big-endian interpretation mode.
bool Type::IsBigEndian()
{
	return bigEndian;
}



// EndianString:
// Get a string representing the endian mode ("LE" or "BE").
string Type::EndianString()
{
	return bigEndian ? "BE" : "LE";
}



// Type:
// Default constructor. Sets type to H1.
Type::Type()
	: length(1), block(1), type('H')
{
}



// Read:
// Interpret the given location as this type. The function calling this one is
// responsible for checking that (it + this->ElementSize() <= end of string).
string Type::Read(string::const_iterator it) const
{
	ostringstream out;

	if(type == 'H')
	{
		string::const_iterator end = it + block;
		if(bigEndian)
			while(it != end)
				out<<HexByteString(*it++);
		else
			while(it != end)
				out<<HexByteString(*--end);
	}
	else if(type == 'C')
	{
		if(*it < ' ')
		{
			if(*it == '\0')
				out<<"\\0";
			else if(*it == '\a')
				out<<"\\a";
			else if(*it == '\b')
				out<<"\\b";
			else if(*it == '\f')
				out<<"\\f";
			else if(*it == '\n')
				out<<"\\n";
			else if(*it == '\r')
				out<<"\\r";
			else if(*it == '\t')
				out<<"\\t";
			else if(*it == '\v')
				out<<"\\v";
			else
				out<<"\\x"<<HexByteString(*it);
		}
		else
			out<<*it;
	}
	else if(type == 'B')
	{
		unsigned char data = *it;
		for(int i = 0; i < 8; ++i)
		{
			out.put((data >> 7) + '0');
			data <<= 1;
		}
	}
	else if(block == 1)
	{
		if(type == 'I')
			out<<static_cast<int>(*it);
		else if(type == 'U')
			out<<static_cast<int>(static_cast<unsigned char>(*it));
	}
	else
	{
		// Test the local endianness.
		static const unsigned short ENDIAN_TEST = 0x0100;
		static const bool LOCAL_ENDIAN = (*reinterpret_cast<const char *>(&ENDIAN_TEST) != 0);

		// Copy the data, reversing it if its endianness does not match the processor.
		string::const_iterator end = it + block;
		static char data[8];
		if(bigEndian == LOCAL_ENDIAN)
			copy(it, end, data);
		else
			reverse_copy(it, end, data);

		// Interpret the data.
		if(type == 'I')
		{
			if(block == 2)
				out << to<int16_t>(data);
			else if(block == 4)
				out << to<int32_t>(data);
			else if(block == 8)
				out << to<int64_t>(data);
		}
		else if(type == 'U')
		{
			if(block == 2)
				out << to<uint16_t>(data);
			else if(block == 4)
				out << to<uint32_t>(data);
			else if(block == 8)
				out << to<uint64_t>(data);
		}
		else if(type == 'F')
		{
			if(block == 4)
				out << to<float>(data);
			else if(block == 8)
				out << to<double>(data);
		}
	}

	return out.str();
}



// SetElementSize:
// Set the number of bytes per element. Return false if the given length is not valid.
bool Type::SetElementSize(int elementSize)
{
	if((type == 'C' || type == 'B') && 
			elementSize != 1)
		return false;
	
	// Hex data may be any width.
	if(type == 'H' && elementSize <= 0)
		return false;

	if((type == 'I' || type == 'U') && 
			elementSize != 1 && elementSize != 2 && elementSize != 4 && elementSize != 8)
		return false;

	if(type == 'F' && 
			elementSize != 4 && elementSize != 8)
		return false;

	block = static_cast<char>(elementSize);
	return true;
}



// ElementSize:
// Get the number of bytes per element.
int Type::ElementSize() const
{
	return block;
}



// SetTotalBytes:
// Set the total length. Return false if the given length is not valid.
bool Type::SetTotalBytes(int totalBytes)
{
	if(totalBytes < 0)
		return false;

	length = totalBytes;
	return true;
}



// TotalBytes:
// Get the total length of the data.
int Type::TotalBytes() const
{
	return (length > block) ? length : block;
}



// SetDataType:
// Set the interpretation type. Return false if the given type is not valid.
// H = hex, C = character, I = signed integer, U = unsigned integer, F = float.
// Either uppercase or lowercase characters for the above are acceptable.
bool Type::SetDataType(char typeIdentifier)
{
	// Convert to upper case.
	if(typeIdentifier >= 'a' && typeIdentifier <= 'z')
		typeIdentifier += 'A' - 'a';

	// Check that the type is valid, and set the default byte sizes.
	if(typeIdentifier == 'H')
		block = 1;
	else if(typeIdentifier == 'C')
		block = 1;
	else if(typeIdentifier == 'B')
		block = 1;
	else if(typeIdentifier == 'I')
		block = 1;
	else if(typeIdentifier == 'U')
		block = 1;
	else if(typeIdentifier == 'F')
		block = 4;
	else if(typeIdentifier == 'D')
	{
		block = 8;
		typeIdentifier = 'F';
	}
	else if(typeIdentifier == 'S')
	{
		block = 2;

		if(type != 'U')
			type = 'I';

		return true;
	}
	else if(typeIdentifier == 'L')
	{
		if((type == 'U' || type == 'I') && block == 4)
			block = 8;
		else
			block = 4;
		
		if(type != 'U')
			type = 'I';

		return true;
	}
	else
		return false;

	// If it's a valid type, save it.
	type = typeIdentifier;
	return true;
}



// DataType:
// Get the current data type.
char Type::DataType() const
{
	return type;
}



// TypeString:
// Get the string defining this type.
// For example, "I4" means 4-byte signed integer.
string Type::TypeString() const
{
	string response(2, type);
	response[1] = '0' + block;
	return response;
}



// HexByteString:
// Convert the given character into a string giving its hexadecimal representation.
const string &Type::HexByteString(unsigned char c)
{
	static string s(2, 'x');

	s[0] = (c / 16) + '0';
	if(s[0] > '9')
		s[0] += 'a' - ('9' + 1);

	s[1] = (c & 0xF) + '0';
	if(s[1] > '9')
		s[1] += 'a' - ('9' + 1);

	return s;
}



bool Type::bigEndian = false;



/* Copyright (c) 2008 Michael Zahniser

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE. */
